package com.topscore.uke.ui.activities;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.StrikethroughSpan;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.kingja.loadsir.callback.Callback;
import com.kingja.loadsir.core.LoadService;
import com.kingja.loadsir.core.LoadSir;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.topscore.uke.R;
import com.topscore.uke.entities.SearchResultBean;
import com.topscore.uke.mvp.contractors.GetStuffListContractor;
import com.topscore.uke.mvp.presenters.GetStuffListPresenter;
import com.topscore.uke.ui.BaseCompatActivity;
import com.topscore.uke.ui.dialog.ShareDialog;
import com.topscore.uke.ui.loadsir_callback.ErrorCallBack;
import com.topscore.uke.ui.widgets.DividerGridItemDecoration;
import com.topscore.uke.ui.widgets.RecyclerAdapterLoadMoreView;
import com.topscore.uke.utils.DisplayImageOptionsManager;

import java.text.DecimalFormat;
import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;

public class SearchResultActivity extends BaseCompatActivity implements GetStuffListContractor.View, View.OnClickListener {

    @Bind(R.id.search_edt)
    EditText searchEdt;
    @Bind(R.id.tool_bar)
    Toolbar toolBar;
    @Bind(R.id.filter_bar)
    RelativeLayout filterBar;
    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.composite_tv)
    TextView compositeTv;
    @Bind(R.id.filter_composite)
    LinearLayout filterComposite;
    @Bind(R.id.latest_tv)
    TextView latestTv;
    @Bind(R.id.filter_latest)
    LinearLayout filterLatest;
    @Bind(R.id.price_tv)
    TextView priceTv;
    @Bind(R.id.price_sort_iv)
    ImageView priceSortIv;
    @Bind(R.id.filter_price)
    LinearLayout filterPrice;

    private DecimalFormat mDecimalFormat = new DecimalFormat("0");

    private BaseQuickAdapter<SearchResultBean, BaseViewHolder> mAdapter;

    private String mSearchWord;

    private GetStuffListContractor.Presenter mPresenter = new GetStuffListPresenter(this);

    private LoadService mLoadService;


    private final int _FilterComposite = 0,
            _FilterLatest = 1,
            _FilterPriceAsc = 2,
            _FilterPriceDesc = 3;

    private int mCurrentFilter = 0;
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_commodity_search, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSearchWord = getIntent().getStringExtra("search_word");
        setContentView(R.layout.activity_search_result);
        ButterKnife.bind(this);
        toolBar.setTitle("");
        setSupportActionBar(toolBar);
        initViews();
    }

    private void initViews() {
        initAdapter();
        searchEdt.setText(mSearchWord);
        mLoadService = LoadSir.getDefault().register(recyclerView, new Callback.OnReloadListener() {
            @Override
            public void onReload(View v) {

            }
        });
        recyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
        recyclerView.addItemDecoration(new DividerGridItemDecoration(this, R.drawable.search_result_divider));
        recyclerView.setAdapter(mAdapter);
        filterComposite.setOnClickListener(this);
        filterLatest.setOnClickListener(this);
        filterPrice.setOnClickListener(this);
        setupFilterViews(_FilterComposite);
        initData();
    }

    private void initData() {
        mPresenter.getStuffByKeyWords(mSearchWord);
//        List<SearchResultBean> searchList = new ArrayList<>();
//        for (int i = 0; i < 17; i++) {
//            SearchResultBean bean = new SearchResultBean();
//            bean.setImage("http://kisscat.com.cn/Uploads/Images/2017031562a5dfe59b047bb18bc0ef2ac9e80e34.jpg");
//            bean.setPriceTag(800);
//            bean.setPrice(699);
//            bean.setTitle("接吻猫橘红色漆皮平底单鞋");
//            searchList.add(bean);
//        }
//        mAdapter.setNewData(searchList);
    }

    private void initAdapter() {
        mAdapter = new BaseQuickAdapter<SearchResultBean, BaseViewHolder>(R.layout.stuff_search_item, new ArrayList<>()) {
            @Override
            protected void convert(BaseViewHolder holder, SearchResultBean item) {
                ImageLoader.getInstance().displayImage(item.getImage(), (ImageView) holder.getView(R.id.image_iv), DisplayImageOptionsManager.getInstance().getDefaultOptions());
                holder.setText(R.id.item_title, item.getTitle())
                        .setText(R.id.price_tv, String.format(getResources().getString(R.string.price), mDecimalFormat.format(item.getPrice())));
                SpannableString originalPrice = new SpannableString(String.format(getResources().getString(R.string.price), mDecimalFormat.format(item.getPriceTag())));
                originalPrice.setSpan(new StrikethroughSpan(), 0, originalPrice.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                holder.setText(R.id.original_price_tv, originalPrice);
                holder.getView(R.id.share).setOnClickListener(view ->{});
                holder.getConvertView().setOnClickListener(view -> {
                    Intent intent = new Intent(mContext, ProductDetailActivity.class);
                    startActivity(intent);
                });
            }
        };
        mAdapter.setEnableLoadMore(true);
        mAdapter.setOnLoadMoreListener(() -> mPresenter.getNextPage(), recyclerView);
        mAdapter.setLoadMoreView(new RecyclerAdapterLoadMoreView());
        mAdapter.setEmptyView(getLayoutInflater().inflate(R.layout.empty_view, (ViewGroup) recyclerView.getParent(), false));
    }

    private void setupFilterViews(int filterCode) {
        compositeTv.setTextColor(Color.parseColor("#333333"));
        latestTv.setTextColor(Color.parseColor("#333333"));
        priceTv.setTextColor(Color.parseColor("#333333"));
        priceSortIv.setVisibility(View.GONE);
        switch (filterCode) {
            case _FilterComposite:
                compositeTv.setTextColor(getResources().getColor(R.color.colorPrimary));
                mCurrentFilter = _FilterComposite;
                break;
            case _FilterLatest:
                latestTv.setTextColor(getResources().getColor(R.color.colorPrimary));
                mCurrentFilter = _FilterLatest;
                break;
            case _FilterPriceAsc:
                priceSortIv.setVisibility(View.VISIBLE);
                priceTv.setTextColor(getResources().getColor(R.color.colorPrimary));
                priceSortIv.setImageResource(R.mipmap.filter_ascending);
                mCurrentFilter = _FilterPriceAsc;
                break;
            case _FilterPriceDesc:
                priceSortIv.setVisibility(View.VISIBLE);
                priceTv.setTextColor(getResources().getColor(R.color.colorPrimary));
                priceSortIv.setImageResource(R.mipmap.filter_descending);
                mCurrentFilter = _FilterPriceDesc;
                break;
        }
    }

    @Override
    public BaseQuickAdapter getRecyclerAdapter() {
        return mAdapter;
    }

    @Override
    public LoadService getLoadService() {
        return mLoadService;
    }

    @Override
    public void onPageEnd() {

    }

    @Override
    public void onLoading(String loadingMessage) {
    }

    @Override
    public void onLoadFinished() {
        mLoadService.showSuccess();
    }

    @Override
    public void onFail(int code, String errorMessage) {
        mLoadService.showCallback(ErrorCallBack.class);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.filter_composite:
                if (mCurrentFilter != _FilterComposite) {
                    setupFilterViews(_FilterComposite);
                    mPresenter.getStuffBySort(_FilterComposite);
                }
                break;
            case R.id.filter_latest:
                if (mCurrentFilter != _FilterLatest) {
                    setupFilterViews(_FilterLatest);
                    mPresenter.getStuffBySort(_FilterLatest);
                }
                break;
            case R.id.filter_price:
                switch (mCurrentFilter) {
                    case _FilterPriceAsc:
                        setupFilterViews(_FilterPriceDesc);
                        mPresenter.getStuffBySort(_FilterPriceDesc);
                        break;
                    case _FilterPriceDesc:
                        setupFilterViews(_FilterPriceAsc);
                        mPresenter.getStuffBySort(_FilterPriceAsc);
                        break;
                    default:
                        setupFilterViews(_FilterPriceAsc);
                        mPresenter.getStuffBySort(_FilterPriceAsc);
                        break;
                }
                break;
        }
    }
}
